<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body>
    <form name="form">
      <p>
        用户名
        <input type="text" name="username" />
      </p>
      <p>
        <button type="button" data-action="submit">提交</button>
      </p>
    </form>
    <script>
      const form = document.form;

      function valid() {}

      const actions = {
        submit() {
          // 表单验证
          // 1. 获取验证字符
          const value = form.username.value;
          // 2. 设置验证规则
          const reg = /^[a-z]{3,18}$/;
          // 3. 验证并输出验证结果
          if (reg.test(value)) {
            console.log("success");
          } else {
            console.log("error");
          }
        },
      };

      form.onclick = function (e) {
        const action = e.target.dataset.action;
        if (action === undefined || actions[action] === undefined) return;
        actions[action].call(e.target);
      };
    </script>
  </body>
</html>
